#include <header.h>
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);

	char *port = "8080";
	char *ip = "192.168.169.128";
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	ERROR_CHECK(socket_fd, -1, "socket");

	// 端口复用,?有问题
	int reuse = 1;
	setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse);


	struct sockaddr_in serveraddr;
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(port));
	serveraddr.sin_addr.s_addr = inet_addr(ip);
	int ret_bind = bind(socket_fd, (struct sockaddr*)&serveraddr, sizeof serveraddr);
	ERROR_CHECK(ret_bind, -1, "bind");
	
	int ret_listen = listen(socket_fd, 10);
	ERROR_CHECK(ret_listen, -1, "listen");


	// 阻塞函数,哪里有问题？
	int socket_fd_new = accept(socket_fd, NULL, NULL);
	ERROR_CHECK(socket_fd_new, -1, "accept");

	fd_set set;
	FD_ZERO(&set);
	while(1){
		FD_SET(STDIN_FILENO, &set);
		FD_SET(socket_fd_new, &set);
		int res = select(10, &set, NULL, NULL, NULL);
		ERROR_CHECK(res, -1, "select");
		
		
		char buf[1 << 10] = {0};
		if(FD_ISSET(STDIN_FILENO, &set)){
			__bzero(buf, sizeof buf);
			read(STDIN_FILENO, buf, sizeof buf);
			send(socket_fd_new, buf, sizeof buf, 0);
		}
		if(FD_ISSET(socket_fd_new, &set)){
			__bzero(buf, sizeof buf);
			ssize_t byte = recv(socket_fd_new, buf, sizeof buf, 0);
			if(byte == 0){
				printf("对方已断开\n");
				break;
			}

			printf("clent:%s\n", buf);		
		}
	}
	close(socket_fd_new);
	close(socket_fd);
	return 0;
}